<?php

namespace app\backend\controller;
//导入基类
use app\common\model\UserLevel;
use think\Controller;
use think\facade\Cache;
use think\Session;
use think\Db;
use app\common\model\User as userModel;
use app\common\model\UserLevel as userLevelModel;
use app\common\model\Reward as rewardModel;
use app\common\model\Money as moneyModel;
use app\common\model\IntegralLog as integralLogModel;
use app\common\model\Assets as assetsModel;
use app\langjinmobile\model\Money;
use app\langjinmobile\model\Wbao_detail;


class User extends Controller 
{ 
	public function index(){
		
		return $this->fetch(); 
	}

	/**
    *  会员列表
    */
    public function userList()
    {

        $limit = request()->param('limit');
        $find = request()->param('find');
        if($find){
            //$user_list=userModel::where('nickname','like',"%{$find}%")->whereOr('mobile',$find)->whereOr('id',$find)->paginate($limit);
            $user_list=userModel::alias('u')->join('langjin_money m','u.id = m.userid')->where('u.id',$find)->whereOr('u.nickname','like',"%{$find}%")->whereOr('u.mobile',$find)->paginate($limit);
            $count = userModel::where('id',$find)->count();
        }else{
            $user_list = userModel::alias('u')->join('langjin_money m','u.id = m.userid')->paginate($limit);
            $count = userModel::count();
        }
       foreach($user_list as $key=>$value){
           $number = 0;
           $level = ['0'=>'普通会员','1'=>'VIP'];
           $sex = ['0'=>'未知','1'=>'男','2'=>'女'];
           $number = userModel::where('parent_id',$value['id'])->count();
           $user_list[$key]['number']  =$number;
           $user_list[$key]['level'] = $level[$user_list[$key]['user_level']];
           $user_list[$key]['sex1'] = $sex[$user_list[$key]['sex']];
       }
        if ($user_list) {
            $data = ['code' => 0, 'msg' => '用户列表', 'count' => $count, 'data' => $user_list->items()];
            return json($data);
        } else {
            $data = ['code' => 0, 'msg' => '用户列表', 'count' => $count, 'data' => array()];
            return json($data);
        }

    }
    /**
    *  添加会员
    */
    public function addUser()
    {   
        
        if (request()->isPost()) {
            $info = input('post.');
            $info['nickname'] = $info['name'];//昵称
            unset($info['name']);
            $img_obj=request()->file();
            if(isset($img_obj['titleFile'])){
                $file=$img_obj['titleFile'];
                $img = $file->validate(['size' => 2048000, 'ext' => 'jpg,png,gif'])->move('uploads');
                if ($img) {
                    // 成功上传后 获取上传信息
                    // 输出 42a79759f284b767dfcb2a0197904287.jpg
                    $img_name = $img->getSaveName();
                    $info['head_img']="/uploads/$img_name";
                } else {
                    // 上传失败获取错误信息
                    $img_name = $file->getError();
                }  
             }
             //如果没添加头像
             if(!isset($info['head_img'])){
                $info['head_img'] = '/static/langjinmobile/images/userhead_img.png';
             }
             //判断手机号是否注册过
             $user = userModel::where('mobile',$info['mobile'])->find();
             if($user!= ""){
                //$this->error('该手机号已注册');
                return array('code'=>'0','msg'=>'该手机号已注册');
             }

             //path路径
             if($info['parent_id'] != ""){
                 $last_user = userModel::where('mobile',$info['parent_id'])->whereOr('id',$info['parent_id'])->field('id,path')->find();
                  if(!$last_user){
                      //$this->error('没有该推荐人');
                      return array('code'=>'0','msg'=>'没有该推荐人');
                  }else{
                      //路径path路径
                      $path=$last_user['path'];
                      if(empty($path)){
                        $info['path']=$last_user['id'].',';
                      }else{
                        $info['path']=$path.$last_user['id'].',';
                      }
                      $info['parent_id']=$last_user['id'];
                  }
             }
             // $info['parent_id']?$info['parent_id']:0;
             //1.user表添加数据
             $info['create_time']=time();
             $info['update_time']=time();
             $uid= userModel::insertGetId($info);//user表
            //3注册money表
           $money['userid'] = $uid;
           $money['balance'] = '0';
           $money['integral'] = '0';
           $money['create_time'] = time();
           moneyModel::insert($money);//money表添加数据
           $this->success('添加成功', 'admin/User/userList');

        }
        

        return $this->fetch();
    }


    public function login(){
        if(request()->isAjax()){
            session('userid',input('post.id'));
            $msg=['message'=>'操作成功','status'=>1];
            return json_encode($msg);
        }
        
    }
    /**
    * GMOB GMOD
    */
    public function details()
    {
       if (request()->isPost()) {
        $uid = input('post.userid');
        $atype = input('post.atype');
        $num=input('post.new_num');
        
        Db::startTrans();
        try{
                if(!empty(input('post.integral')) && input('post.integral') !==null){
                    
                    $integral_num=input('post.integral_num');
                    // var_dump($integral_num);die();
                    //判断是增加还是减少
                    if($atype==1){
                        //增加  
                        Money::where('userid',$uid)->setInc('integral',$num);
                        $data=[
                        'userid'=>$uid,
                        'num'=>$num, 
                        'type'=>16,
                        'before_integral'=>$integral_num,
                        'now_integral'=>bcadd($integral_num,$num,4),
                        'create_time'=>time(), 
                        ];
                    }else{
                        //减少
                        Money::where('userid',$uid)->setDec('integral',$num);
                        $data=[
                            'userid'=>$uid,
                            'num'=>$num,
                            'type'=>17,
                            'before_integral'=>$integral_num,
                            'now_integral'=>bcsub($integral_num,$num,4),
                            'create_time'=>time(),
                        ];
                    }
                    Db::table('langjin_integral_log')->insert($data);
                }else{
                 
                    $wallet_num=input('post.wallet_num');
                    //判断是增加还是减少
                    if($atype==1){
                        //增加  
                        Money::where('userid',$uid)->setInc('balance',$num);
                        $data=[
                            'userid'=>$uid, 
                            'money'=>$num, 
                            'type'=>10,
                            'before_wallet'=>$wallet_num, 
                            'now_wallet'=>bcadd($wallet_num,$num,4), 
                            'create_time'=>time(), 
                        ];
                    }else{
                        //减少
                        
                        Money::where('userid',$uid)->setDec('balance',$num);
                        $data=[
                            'userid'=>$uid, 
                            'money'=>$num, 
                            'type'=>11,
                            'before_wallet'=>$wallet_num, 
                            'now_wallet'=>bcsub($wallet_num,$num,4), 
                            'create_time'=>time(), 
                        ];
                    }
                    Db::table('langjin_wallet_log')->insert($data);
                }
                Db::commit(); 
                return $msg=['message'=>'操作成功','status'=>1];
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $msg=['message'=>'操作失败','status'=>2];
            }   
        }
        
        $id = request()->param('id');
        $data = Money::where('userid',$id)->find();
        $assets = assetsModel::where('c_uid',$id)->field('c_uid,c_nums')->find();
        $this->assign('data', $data);
        
        return $this->fetch();
    }


    //个人信息
    public function editUser($id='')
    {
        if (request()->isPost()) {
            $info = input('post.');
            $img_obj=request()->file();
            if(isset($img_obj['titleFile'])){
                $file=$img_obj['titleFile'];
                $img = $file->validate(['size' => 2048000, 'ext' => 'jpg,png,gif'])->move('uploads');
                if ($img) {
                    // 成功上传后 获取上传信息
                    // 输出 42a79759f284b767dfcb2a0197904287.jpg
                    $img_name = $img->getSaveName();
                    $info['head_img']="/uploads/$img_name";
                    //删除之前图片
                    $user = userModel::where('id',$info['id'])->field('head_img')->find();
                    if($user['head_img'] != '' && $user['head_img'] != '/static/mobile/images/userhead_img.png'){
                        //file文件路径
                        $filename = '.'.$user['head_img'];
                        if(file_exists($filename)){
                            unlink($filename);
                        }  
                    }
                } else {
                    // 上传失败获取错误信息
                    $img_name = $file->getError();
                }   
              }
            $edit = userModel::update($info);
            return $edit;
        }
            $id = input('get.id')?input('get.id'):$id;
            $data = userModel::get($id);
            // echo'<pre>';
            // var_dump($data);
            $this->assign('data', $data);
            return $this->fetch();   
    }
    public function vipuser(){
        return $this->fetch();
    }


    /**
    *  禁用用户
    */
    public function editshow(){
        // $data=input('post.');
        $data=array();
        $data['id']=request()->param('id');
        if(request()->param('disable')==0){
            $data['disable']=1;
        }elseif(request()->param('disable')==1){
            $data['disable']=0;
        };
        $edit = userModel::update($data);
         return $edit;
    }
    /**
     *  推荐结构
     */
    public function jiegou()
    {
        if (request()->isPost()){ //搜索
            $id = input('post.id');
            $path=userModel::where('id', $id)->field('id,path,mobile')->find();
            $my = $path;
            $pathid=$path['path'].$id.',';
            $users = userModel::where('path',$pathid)->order('id', 'asc')->field('id,nickname,mobile')->select();
            // foreach ($users as $user) {
            //     $user['mobile'] = substr($user['mobile'], 0, 3)."********";
            // }

        }else{
            //第一人id parent_id=0的
            $users=userModel::where('parent_id',0)->order('id', 'asc')->field('id,nickname,mobile')->select();
            // foreach ($users as $user) {
            //     $user['mobile'] = substr($user['mobile'], 0, 3)."********";
            // }
            $my = '';
        }

        $this->assign('my',$my); //搜索的用户
        $this->assign('users',$users);
        return $this->fetch();
    }
    /**
     * 会员关系
     */
    public function tree()
    {
        //接收传过来的id
        $id = input('post.id');
        //查询这个id下级会员
        //$path = userModel::where('id',$id)->field('path')->find();

        $users = userModel::where('parent_id',$id)->field('id,nickname,mobile')->select();
        // foreach ($users as $user) {
        //     $user['mobile'] = substr($user['mobile'], 0, 3)."********";
        // }
        return $users;

    }
	
}